﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using YiSha.Business.OrganizationManage;
using YiSha.Business.SystemManage;
using YiSha.Entity.SystemManage;
using YiSha.Enum;
using YiSha.IdGenerator;
using YiSha.Model.Result;
using YiSha.Util.Extension;
using YiSha.Web.Code;
using YiSha.Util.Model;
using YiSha.Util;
using YiSha.Entity.OrganizationManage;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using YiSha.Util.EChart;
using System.Collections;
using YiSha.Model.Param.OrganizationManage;

namespace YiSha.Admin.Web.Controllers
{
    public class HomeController : BaseController
    {
        private MenuBLL menuBLL = new MenuBLL();
        private UserBLL userBLL = new UserBLL();
        private LogLoginBLL logLoginBLL = new LogLoginBLL();
        private MenuAuthorizeBLL menuAuthorizeBLL = new MenuAuthorizeBLL();

        #region 视图功能
        [HttpGet]
        [AuthorizeFilter]
        public async Task<IActionResult> Index()
        {
            OperatorInfo operatorInfo = await Operator.Instance.Current();

            TData<List<MenuEntity>> objMenu = await menuBLL.GetList(null);
            List<MenuEntity> menuList = objMenu.Data;
            menuList = menuList.Where(p => p.MenuStatus == StatusEnum.Yes.ParseToInt()).ToList();

            if (operatorInfo.IsSystem != 1)
            {
                TData<List<MenuAuthorizeInfo>> objMenuAuthorize = await menuAuthorizeBLL.GetAuthorizeList(operatorInfo);
                List<long?> authorizeMenuIdList = objMenuAuthorize.Data.Select(p => p.MenuId).ToList();
                menuList = menuList.Where(p => authorizeMenuIdList.Contains(p.Id)).ToList();
            }

            ViewBag.MenuList = menuList;
            ViewBag.OperatorInfo = operatorInfo;
            return View();
        }

        [HttpGet]
        public async Task<IActionResult> Welcome()
        {
            OperatorInfo operatorInfo = await Operator.Instance.Current();
            var userShowData= await userBLL.GetShowUserData(operatorInfo.UserId);

            ViewBag.ShowData=userShowData.Data;
            return View();
        }

        [HttpGet]
        public IActionResult Login()
        {
            if (GlobalContext.SystemConfig.Demo)
            {
                ViewBag.UserName = "admin";
                ViewBag.Password = "123456";
            }
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> LoginOffJson()
        {
            OperatorInfo user = await Operator.Instance.Current();
            if (user != null)
            {
                #region 退出系统
                // 如果不允许同一个用户多次登录，当用户登出的时候，就不在线了
                if (!GlobalContext.SystemConfig.LoginMultiple)
                {
                    await userBLL.UpdateUser(new UserEntity { Id = user.UserId, IsOnline = 0 });
                }

                // 登出日志
                await logLoginBLL.SaveForm(new LogLoginEntity
                {
                    LogStatus = OperateStatusEnum.Success.ParseToInt(),
                    Remark = "退出系统",
                    IpAddress = NetHelper.Ip,
                    IpLocation = string.Empty,
                    Browser = NetHelper.Browser,
                    OS = NetHelper.GetOSVersion(),
                    ExtraRemark = NetHelper.UserAgent,
                    BaseCreatorId = user.UserId
                });

                Operator.Instance.RemoveCurrent();
                new CookieHelper().RemoveCookie("RememberMe");

                return Json(new TData { Tag = 1 });
                #endregion
            }
            else
            {
                throw new Exception("非法请求");
            }
        }

        [HttpGet]
        public IActionResult NoPermission()
        {
            return View();
        }

        [HttpGet]
        public IActionResult Error(string message)
        {
            ViewBag.Message = message;
            return View();
        }

        [HttpGet]
        public IActionResult Skin()
        {
            return View();
        }
        #endregion

        #region 获取数据
        public IActionResult GetCaptchaImage()
        {
            string sessionId = GlobalContext.ServiceProvider?.GetService<IHttpContextAccessor>().HttpContext.Session.Id;

            Tuple<string, int> captchaCode = CaptchaHelper.GetCaptchaCode();
            byte[] bytes = CaptchaHelper.CreateCaptchaImage(captchaCode.Item1);
            new SessionHelper().WriteSession("CaptchaCode", captchaCode.Item2);
            return File(bytes, @"image/jpeg");
        }
        #endregion

        #region 提交数据
        [HttpPost]
        public async Task<IActionResult> LoginJson(string userName, string password, string captchaCode)
        {
            TData obj = new TData();
            if (string.IsNullOrEmpty(captchaCode))
            {
                obj.Message = "验证码不能为空";
                return Json(obj);
            }
            if (captchaCode != new SessionHelper().GetSession("CaptchaCode").ParseToString())
            {
                obj.Message = "验证码错误，请重新输入";
                return Json(obj);
            }
            TData<UserEntity> userObj = await userBLL.CheckLogin(userName, password, (int)PlatformEnum.Web);
            if (userObj.Tag == 1)
            {
                await new UserBLL().UpdateUser(userObj.Data);
                await Operator.Instance.AddCurrent(userObj.Data.WebToken);
            }

            string ip = NetHelper.Ip;
            string browser = NetHelper.Browser;
            string os = NetHelper.GetOSVersion();
            string userAgent = NetHelper.UserAgent;

            Action taskAction = async () =>
            {
                LogLoginEntity logLoginEntity = new LogLoginEntity
                {
                    LogStatus = userObj.Tag == 1 ? OperateStatusEnum.Success.ParseToInt() : OperateStatusEnum.Fail.ParseToInt(),
                    Remark = userObj.Message,
                    IpAddress = ip,
                    IpLocation = IpLocationHelper.GetIpLocation(ip),
                    Browser = browser,
                    OS = os,
                    ExtraRemark = userAgent,
                    BaseCreatorId = userObj.Data?.Id
                };

                // 让底层不用获取HttpContext
                logLoginEntity.BaseCreatorId = logLoginEntity.BaseCreatorId ?? 0;

                await logLoginBLL.SaveForm(logLoginEntity);
            };
            AsyncTaskHelper.StartTask(taskAction);

            obj.Tag = userObj.Tag;
            obj.Message = userObj.Message;
            return Json(obj);
        }

        [HttpPost]
        public async Task<IActionResult> GetEchartDataJson()
        {
            TData<EchartData> obj = new TData<EchartData>();
            obj.Data = new EchartData();
            OperatorInfo operatorInfo = await Operator.Instance.Current();
            TData<List<EchartParam>> echartParamList = await userBLL.GetEchartData(operatorInfo.UserId);
            ArrayList showClickList = new ArrayList();
            ArrayList showViewList = new ArrayList();

            ArrayList dateList = new ArrayList() {
                           DateTime.Now.AddDays(-6).ToString("yyyy-MM-dd"),
                           DateTime.Now.AddDays(-5).ToString("yyyy-MM-dd"),
                           DateTime.Now.AddDays(-4).ToString("yyyy-MM-dd"),
                           DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd"),
                           DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd"),
                           DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") ,
                           DateTime.Now.ToString("yyyy-MM-dd") };
            if (echartParamList.Data != null && echartParamList.Data.Count > 0)
            {
                foreach (var item in dateList)
                {
                    var echartParam = echartParamList.Data.Where(t => t.BaseCreateTime == item.ToString()).FirstOrDefault();
                    if (echartParam != null && !string.IsNullOrEmpty(echartParam.BaseCreateTime))
                    {
                        showClickList.Add(echartParam.ShowClick);
                        showViewList.Add(echartParam.ShowView);
                    }
                    else
                    {
                        showClickList.Add("0");
                        showViewList.Add("0");
                    }

                }
            }
            var ss= EChartInit(dateList, showViewList, showClickList, "bar").ToString();
            obj.Data.BarData = EChartInit(dateList, showViewList, showClickList, "bar").ToString();
            obj.Data.LineData = EChartInit(dateList, showViewList, showClickList, "line").ToString();
            obj.Tag = 1;
            return Json(obj);
        }
        #endregion
        /// <summary>
        /// 柱状
        /// </summary>
        /// <returns></returns>
        public static EChartOption EChartInit(ArrayList dateList, ArrayList viewList, ArrayList clickList, string type)
        {
            EChartOption option = new EChartOption()
            {
                title = new EChartTitle()
                {
                    text = "流量统计"
                },
                tooltip = new EChartTooltip()
                {
                    trigger = "axis"
                },
                legend = new EChartLegend()
                {
                    data = new ArrayList() { "浏览量", "点击量" }
                },
                calculable = true,
                grid = new EChartGrid()
                {
                    left = "3%",
                    right = "4%",
                    bottom = "3%",
                    containLabel = true
                },
                xAxis = new List<EChartxAxis>()
                {
                  new EChartxAxis(){
                      type="category",
                      splitLine=new SplitLine(){
                          show=false
                       },
                       data = dateList,
                      boundaryGap=true
                  }
               },
                yAxis = new List<EChartyAxis>()
             {
                  new EChartyAxis(){
                      type="value",
                      splitLine=new SplitLine(){ show=false},
                      min=null,max=null
                   }

             },
                series = new List<EChartSeries>()
             {
                  new EChartSeries(){
                       name="浏览量",
                      type=type,
                      data = viewList
                    },
                    new EChartSeries(){
                       name="点击量",
                      type=type,
                      data =clickList
                    }
             }
            };
            return option;
        }

        /// <summary>
        /// 散点图
        /// </summary>
        /// <returns></returns>
        public static EChartOption scatterInit()
        {
            EChartOption option = new EChartOption()
            {
                tooltip = new EChartTooltip()
                {
                    trigger = "item",
                    formatter = "{b} : {c} ({d}%)",
                    axisPointer = new EChartAxisPointer()
                    {
                        type = "line",
                        axis = "x",
                        lineStyle = new LineStyle()
                        {
                            color = "#000"
                        }
                    }
                },
                color = new ArrayList(),
                legend = new EChartLegend() { orient = "horizontal", x = "center", data = new ArrayList() },
                xAxis = new List<EChartxAxis>(){ new EChartxAxis(){
             splitLine=new SplitLine(){
              show=false
             },
             type="category",
             data=new ArrayList(),

            }},
                yAxis = new List<EChartyAxis>() { new EChartyAxis() {
                type = "value",
                nameLocation = "end",
                splitNumber=5,
                name="万吨",
                min="auto",
                max="auto",
                data=new ArrayList(),
                boundaryGap=false,
                splitLine = new SplitLine() { show = false }

                } },
                animation = true,
                title = new EChartTitle() { },
                series = new List<EChartSeries>(){
        new EChartSeries(){
         type="scatter",
         symbol="none",
          markLine=new MarkLine(){
           silent=true,
           label=new EChartLabel(){normal=new EChartNormal(){show=false}, emphasis=new EChartEmphasis()

{show=false}},
          data=new ArrayList()
          }
        }
        }
            };
            return option;

        }




    }
}
